const express = require('express');
const cors = require('cors');
const axios = require('axios');

const app = express();
const PORT = 3456;

// 中间件
app.use(cors());
app.use(express.json());

// Supabase API 基础 URL
const SUPABASE_API_BASE = 'https://api.supabase.com';

/**
 * 通用代理接口
 * POST /proxy
 *
 * 请求体:
 * {
 *   url: string,        // Supabase API 路径，如 /v1/projects/xxx/config/storage
 *   method: string,     // HTTP 方法: GET, POST, PUT, PATCH, DELETE
 *   data?: object,      // 请求体数据
 *   token: string       // Supabase Access Token
 * }
 */
app.post('/proxy', async (req, res) => {
  const { url, method, data, token } = req.body;

  // 参数验证
  if (!url) {
    return res.status(400).json({ error: 'Missing required parameter: url' });
  }
  if (!method) {
    return res.status(400).json({ error: 'Missing required parameter: method' });
  }
  if (!token) {
    return res.status(400).json({ error: 'Missing required parameter: token' });
  }

  const fullUrl = url.startsWith('http') ? url : `${SUPABASE_API_BASE}${url}`;

  console.log('[Proxy Request]', {
    url: fullUrl,
    method: method,
    data: data,
    hasToken: !!token
  });

  try {
    const response = await axios({
      method: method,
      url: fullUrl,
      data: data,
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
        'Accept': '*/*'
      },
      timeout: 30000
    });

    console.log('[Proxy Response]', {
      status: response.status,
      data: response.data
    });

    res.status(response.status).json(response.data);
  } catch (error) {
    console.error('[Proxy Error]', {
      message: error.message,
      status: error.response?.status,
      data: error.response?.data
    });

    if (error.response) {
      // Supabase API 返回的错误
      res.status(error.response.status).json(error.response.data);
    } else {
      // 网络错误等
      res.status(500).json({
        error: 'Proxy request failed',
        message: error.message
      });
    }
  }
});

/**
 * 健康检查
 */
app.get('/health', (req, res) => {
  res.json({ status: 'ok', timestamp: new Date().toISOString() });
});

/**
 * 根路径
 */
app.get('/', (req, res) => {
  res.json({
    name: 'Supabase Proxy Server',
    version: '1.0.0',
    endpoints: {
      proxy: 'POST /proxy',
      health: 'GET /health'
    }
  });
});

app.listen(PORT, () => {
  console.log(`Supabase Proxy Server running at http://localhost:${PORT}`);
  console.log(`Health check: http://localhost:${PORT}/health`);
});
